﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
// 使用OleDb连接数据库
using System.Data.OleDb;

namespace 实验5_DataTable操作及数据的绑定
{
    public partial class FormMain : Form
    {
        //string myConnString = "Provider=SQLOLEDB;Data Source=LIKEQCPC\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=master";
        string myConnString = "Provider=SQLOLEDB;Data Source=.;Integrated Security=SSPI;Initial Catalog=master";
        OleDbConnection conn = null;
        OleDbCommand cmd = null;
        DataTable dt = null;
        DataView dv = null;
        BindingSource bs = null;

        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            conn = new OleDbConnection();
            conn.ConnectionString = myConnString;
            cmd = new OleDbCommand();
            cmd.Connection = conn;
            cmd.CommandText = "select * from student";

            OleDbDataAdapter adapter = new OleDbDataAdapter();
            adapter.SelectCommand = cmd;

            dt = new DataTable();
            adapter.Fill(dt);

            bs = new BindingSource();
            dv = dt.DefaultView;
            bs.DataSource = dv;
            this.dataGridView1.DataSource = bs;
            this.bindingNavigator1.BindingSource = bs;
        }

        private void tb_Validated(object sender, EventArgs e)
        {
            // 获取当前所选数据行的索引
            int row = dataGridView1.CurrentCell.RowIndex;
            // 修改dataGridView1中显示的数据
            dataGridView1.Rows[row].Cells["SNO"].Value = this.tb_SNO.Text.ToString();
            dataGridView1.Rows[row].Cells["SNAME"].Value = this.tb_SNAME.Text.ToString();
            dataGridView1.Rows[row].Cells["SEX"].Value = this.tb_SEX.Text.ToString();
            dataGridView1.Rows[row].Cells["DEPT"].Value = this.tb_DEPT.Text.ToString();
            dataGridView1.Rows[row].Cells["AGE"].Value = this.tb_AGE.Text.ToString();
            // 更新dataTable
            dt.AcceptChanges();
        }

        private void dataGridView1_SelectionChanged(object sender, EventArgs e)
        {
            DataRowView drv = (DataRowView)bs.Current;
            DataRow dr = drv.Row;
            this.tb_SNO.Text = dr.ItemArray[0].ToString();
            this.tb_SNAME.Text = dr.ItemArray[1].ToString();
            this.tb_SEX.Text = dr.ItemArray[2].ToString();
            this.tb_DEPT.Text = dr.ItemArray[3].ToString();
            this.tb_AGE.Text = dr.ItemArray[4].ToString();
        }

        private void btn_showGirl_Click(object sender, EventArgs e)
        {
            bs = new BindingSource();
            dv = new DataView(dt, "sex = '女'", "sname", DataViewRowState.CurrentRows);
            bs.DataSource = dv;
            this.dataGridView2.DataSource = bs;
        }

    }
}
